#include <iostream>
#include <string>
#include <functional>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <memory>
#include "log.hpp"
using namespace LogModule;

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        return 1;
    }
    ENABLE_CONSOLE_LOG_STRATEGY();
    std::string serve_ip = argv[1];
    int serve_port = std::stoi(argv[2]);
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "socket failsure";
        exit(2);
    }
    // 客户端不用显示绑定在我们第一次发消息的时候就os会自动帮我们绑定客户端机器的ip，端口号随机生成
    sockaddr_in serve;
    bzero(&serve, sizeof(serve));
    socklen_t len = sizeof(serve);
    serve.sin_port = htons(serve_port);
    serve.sin_family = AF_INET;
    serve.sin_addr.s_addr = inet_addr(serve_ip.c_str());
    while (true)
    {
        std::string mesage;
        std::cout << "Please Enter:" << std::endl;
        // 从标准输入流读取mesage
        getline(std::cin, mesage);
        int n = sendto(sockfd, mesage.c_str(), mesage.size(), 0, (sockaddr *)&serve, len);
        (void)n;

        // 收消息
        char buffer[1024];
        sockaddr_in peer;
        bzero(&peer, sizeof(peer));
        socklen_t peerlen=sizeof(peer);
        int m= recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(sockaddr*)&peer,&peerlen);
        if(m>0)
        {
            buffer[m]=0;
            std::cout<<buffer<<std::endl;
        }
    }
    return 0;
}